package com.sfzd5.exam;

import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.otaliastudios.cameraview.CameraListener;
import com.otaliastudios.cameraview.CameraUtils;
import com.otaliastudios.cameraview.CameraView;
import com.otaliastudios.cameraview.Gesture;
import com.otaliastudios.cameraview.GestureAction;
import com.sfzd5.exam.helplibrary.exam.PostAnserResult;

import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;

/**
创建扫描任务和步骤
扫描界面，上面是扫描，下边按扭有：确定，点确定后，将生成预览图片，如果合适，点下一步，不合适点，重新扫描，不可后退扫描上一步，只可退回创建任务页
最终页面，可浏览扫描的各页内容，可提交或重新扫描，重新扫描从第一页开始
提交后显示任务已经完成
 */
public class CameraActivity extends Activity {

    public static final double PageWidthRatio = 0.8;

    Handler childHandler; // 子线程
    Handler mainHandler; // UI线程

    boolean hasSetImageView = false;
    // 很多过程都变成了异步的了，所以这里需要一个子线程的looper

    CameraView camera;
    ImageView imageView;
    Button bt_ok;

    private String[] permissions = {Manifest.permission.CAMERA};
    private int requestPermissionCode = 321;
    private int requestSettingPermissionCode = 123;
    AlertDialog dialog;
    ProgressDialog cameraProgressDialog;
    PApplication app;
    Recognition recognition;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_camera);

        app = (PApplication) getApplication();

        camera = findViewById(R.id.camera);
        camera.mapGesture(Gesture.TAP, GestureAction.FOCUS_WITH_MARKER);

        imageView = findViewById(R.id.imageView);
        bt_ok = findViewById(R.id.bt_ok);

        HandlerThread handlerThread = new HandlerThread("Camera2");
        handlerThread.start();

        childHandler = new Handler(handlerThread.getLooper());
        mainHandler = new Handler(getMainLooper());

        recognition = new Recognition(PageWidthRatio, getExternalCacheDir(), app.getWorkProcess());
        camera.addCameraListener(new CameraListener() {
            @Override
            public void onPictureTaken(byte[] picture) {
                // 拍出的图出，高度成比例，但更宽一些，所以需要裁剪
                CameraUtils.decodeBitmap(picture, new CameraUtils.BitmapCallback() {
                    @Override
                    public void onBitmapReady(Bitmap bitmap) {
                        CameraAsyncTask task = new CameraAsyncTask();
                        task.execute(bitmap);
                    }
                });
            }
        });

        bt_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (camera == null) {
                    return;
                }

                cameraProgressDialog = new ProgressDialog(CameraActivity.this);
                cameraProgressDialog.setMessage("识别答题卡");
                cameraProgressDialog.show();

                camera.capturePicture();
            }
        });
    }

    class CameraAsyncTask extends AsyncTask<Bitmap, Integer, PostAnserResult> {
        @Override
        protected void onPostExecute(PostAnserResult postAnserResult) {
            super.onPostExecute(postAnserResult);
            cameraProgressDialog.hide();
            Intent intent = new Intent(CameraActivity.this, MainActivity.class);
            app.result = postAnserResult;
            startActivity(intent);
        }

        @Override
        protected PostAnserResult doInBackground(Bitmap... bitmaps) {
            PostAnserResult examResult = recognition.PageRecognition(bitmaps[0], camera.getWidth(), camera.getHeight());
            return examResult;
        }
    }

    public void loadOpenCV()
    {
        if (!OpenCVLoader.initDebug()) {
            Log.d("CameraActivity", "Internal OpenCV library not found. Using OpenCV Manager for initialization");
            OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_3_0_0, this, mLoaderCallback);
        } else {
            Log.d("CameraActivity", "OpenCV library found inside package. Using it!");
            mLoaderCallback.onManagerConnected(LoaderCallbackInterface.SUCCESS);
        }
    }

    //OpenCV 库加载并初始化成功后的回调函数
    private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {

        @Override
        public void onManagerConnected(int status) {
            // TODO Auto-generated method stub
            switch (status){
                case BaseLoaderCallback.SUCCESS:
                    Log.i("CameraActivity", "成功加载");
                    break;
                default:
                    super.onManagerConnected(status);
                    Log.i("CameraActivity", "加载失败");
                    break;
            }

        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        checkPermission();
        loadOpenCV();
    }

    @Override
    protected void onPause() {
        super.onPause();
        camera.stop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        camera.destroy();
    }

    //取消退出
    @Override
    public void onBackPressed() {
        setResult(Activity.RESULT_CANCELED);
        finish();
    }

    void startCamera() {
        imageView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if(!hasSetImageView) {
                    hasSetImageView = true;
                    imageView.setImageBitmap(
                        app.getWorkProcess().createCurPageFrontImage(imageView.getWidth(), imageView.getHeight(), PageWidthRatio)
                    );
                    //开启中心自动对焦
                    //camera.startAutoFocus(camera.getWidth() / 2, camera.getHeight() / 2);
                }
            }
        });
        camera.start();
    }

    /////////////////////////////////////////
    //下面全是权限检测
    ////////////////////////////////////////
    void checkPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int i = checkSelfPermission(permissions[0]);
            if (i != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(permissions, requestPermissionCode);
            } else {
                startCamera();
            }
        } else {
            startCamera();
        }
    }

    // 下面是用户权限相关代码 申请 的回调方法
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == requestPermissionCode) {
            if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                // 判断用户是否 点击了不再提醒。(检测该权限是否还可以申请)
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
                    boolean b = shouldShowRequestPermissionRationale(permissions[0]);
                    if (!b) {
                        showDialogTipUserGoToAppSettting();
                    } else {
                        finish();
                    }
                }
            } else {
                startCamera();
            }
        }
    }

    // 提示用户去应用设置界面手动开启权限
    private void showDialogTipUserGoToAppSettting() {
        dialog = new AlertDialog.Builder(this)
                .setTitle("相机不可用")
                .setMessage("请在-应用设置-权限-中，允许本程序的相机使用权限")
                .setPositiveButton("立即开启", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 跳转到应用设置界面
                        goToAppSetting();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                }).setCancelable(false).show();
    }

    // 跳转到当前应用的设置界面
    private void goToAppSetting() {
        Intent intent = new Intent();
        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", getPackageName(), null);
        intent.setData(uri);
        startActivityForResult(intent, requestSettingPermissionCode);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == requestSettingPermissionCode) {
            if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                // 检查该权限是否已经获取
                int i = checkSelfPermission(permissions[0]);
                // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
                if (i != PackageManager.PERMISSION_GRANTED) {
                    // 提示用户应该去应用设置界面手动开启权限
                    if (dialog != null && dialog.isShowing()) {
                        dialog.dismiss();
                    }
                    Toast.makeText(this, "未设置权限", Toast.LENGTH_SHORT).show();
                    finish();
                } else {
                    if (dialog != null && dialog.isShowing()) {
                        dialog.dismiss();
                    }
                    Toast.makeText(this, "权限获取成功", Toast.LENGTH_SHORT).show();
                    startCamera();
                }
            }
        }
    }

}
